package manager

import (
	"dragonfly/common/tcp"
	"dragonfly/common/types"
)

type callback struct {
}

func (cb *callback) OnConnected(conn *tcp.TCPConn) {
	manager.log.Info().Msgf("callback: %s connected.", conn.GetRemoteAddr().String())
}

//链接断开回调
func (cb *callback) OnDisconnected(conn *tcp.TCPConn) {
	manager.log.Info().Msgf("callback: %s disconnect.", conn.GetRemoteAddr().String())
}

//错误回调
func (cb *callback) OnError(err error) {
	manager.log.Error().Msgf("callback: %v .", err)
}

//消息处理回调
func (cb *callback) OnMessage(conn *tcp.TCPConn, p tcp.Packet) {
	defer func() {
		if r := recover(); r != nil {
			manager.log.Error().Msgf("Recovered in OnMessage: %v", r)
		}
	}()
	pkt := p.(*tcp.DefaultPacket)
	cb.dispatch(conn, pkt)
}

func (cb *callback) dispatch(conn *tcp.TCPConn, pkt *tcp.DefaultPacket) {
	switch pkt.Type {
	case types.MsgSendHeartbeat:
		hb := &types.HeartBeat{}
		if err := hb.Decode(pkt.Body); err != nil {
			manager.log.Error().Msgf("%s", err)
			return
		}
		manager.log.Info().Msgf("Agent reply: %s, %s", types.MsgTextMap[pkt.Type], hb.Message)
	default:
		manager.log.Error().Msgf("unsupport packet type %v", pkt.Type)
		conn.Close()
	}
}
